package com.efast.cafe.commponent.es.socketio.listener;

import java.io.Serializable;
import java.util.List;

import org.slf4j.event.Level;

import com.cafeauto.socketio.SocketCallbackData;
import com.cafeauto.socketio.SocketIOData;
import com.cafeauto.socketio.SocketOutData;
import com.corundumstudio.socketio.AckCallback;
import com.corundumstudio.socketio.SocketIOClient;
import com.efast.cafe.commponent.es.socketio.util.SocketIOUtil;
import com.efast.cafe.commponent.log.ext.CafeLogger;
import com.efast.cafe.commponent.log.ext.CafeLoggerFactory;
import com.efast.cafe.framework.constant.FrameConstant;
import com.efast.cafe.framework.json.JSONObject;
import com.mongodb.util.JSON;


/**
 * 订阅redis消息队列
 * @author fxm
 *
 */
public class PushMessageDelegateListenerImpl implements MessageDelegate{

	private final static CafeLogger log = CafeLoggerFactory.getLogger(PushMessageDelegateListenerImpl.class);
	
	 
	    @Override
	    public void handleMessage(String message, String channel) {
	        //if(message instanceof SocketIOData){
	    	net.sf.json.JSONObject msg = net.sf.json.JSONObject.fromObject(message);
	    	SocketIOData data = (SocketIOData)net.sf.json.JSONObject.toBean(msg,SocketIOData.class);
	        	SocketIOClient client = SocketIOUtil.getSocketIOClient(data.getUid());
	        	if(data.getEventName().equals(FrameConstant.SOCKET_DISCONNECT_EVENT)){
	        		if(client!=null){
	        			client.disconnect();
	        		}
	        		return;
	        	}
	    		if(null!=client){
	    			AckCallback<SocketCallbackData> ack = new AckCallback<SocketCallbackData>(SocketCallbackData.class, 20) {
						/**
						 * 客户端回调 
						 */
						@Override
						public void onSuccess(SocketCallbackData data) {
							log.info("Received callback data :"+new JSONObject(data).toString());
						}
					};
	    			
    				if(client.isChannelOpen()){
    					SocketOutData out = new SocketOutData(data.getId(),data.getBusObject(),true);
    					try{
    						client.sendEvent(data.getEventName(),ack,out);
    						log.info("send event message :" + new JSONObject(out).toString());
    					}catch(Exception e){
    						e.printStackTrace();
    						if(e instanceof NullPointerException){
    							//客户端20秒之内没有返回信息给服务端
    							log.cacheLog(Level.ERROR, new JSONObject(out).toString(), "socket.io_event:"+data.getEventName()+",CLIENT_CALLBACK_TIMEOUT");
    						}else{
	    						log.cacheLog(Level.ERROR, new JSONObject(out).toString(), "socket.io_event:"+data.getEventName()+",SYSTEM_ERROR.e:"+e.getMessage());
    						}
    					}
    					
    				}else{
    					log.warn("client sessionId:"+client.getSessionId().toString()+",uid:"+data.getUid()+",通道已关闭，不能推送消息。");
    				}
	    				
	    		}else{
	    			log.warn("send event to client error,client is off line,eventName:"+data.getEventName()+",to uid:"+data.getUid());
	    		}
	        	
	        	
	        	
	        }
	 //  }


}
